<!-- 插件管理页 -->
<template>
  <div class="plugin-management">
    <!-- 查询表单 -->
    <el-form class="demo-form-inline" ref="formRef" :model="queryForm" label-width="100px" size="small" inline>
      <el-form-item label="插件名称" prop="name">
        <el-input v-model="queryForm.name" placeholder="插件名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="插件类型" prop="type">
        <el-select v-model="queryForm.type" placeholder="请选择插件类型" clearable>
          <el-option v-for="type in pluginTypes" :key="type.value" :label="type.label" :value="type.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchPlugins">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetData">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="el-row">
      <el-button type="success" icon="el-icon-plus" plain size="small" @click="handleAdd">新增插件</el-button>
      <el-button type="danger" icon="el-icon-delete" plain size="small" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
    </div>

    <!-- 插件列表 -->
    <el-table
      :data="tableData"
      height="100%"
      style="width: 100%; "
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="name" label="插件名称"></el-table-column>
      <el-table-column prop="type" label="插件类型"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column label="操作" width="240" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleEnableDisable(scope.row)">{{ scope.row.status === '启用' ? '禁用' : '启用' }}</el-button>
          <el-button type="text" @click="handleTest(scope.row)">测试</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      style="text-align: right"
    ></el-pagination>

    <!-- 新增/编辑插件对话框 -->
    <PluginForm
      :visible.sync="dialogVisible"
      :dialogTitle="dialogTitle"
      :formData="form"
      :pluginTypes="pluginTypes"
      @submit="handleSubmit"
    />

    <!-- 插件详情对话框 -->
    <PluginDetail
      :visible.sync="detailVisible"
      :formData="selectedRow"
    />
  </div>
</template>

<script>
import PluginForm from './components/PluginForm.vue';
import PluginDetail from './components/PluginDetail.vue';

export default {
  name: "PluginManagement",
  components: { PluginForm, PluginDetail },
  data() {
    return {
      queryForm: {
        name: "",
        type: ""
      },
      totalTableData: [
        // 示例数据
        { id: 1, name: 'SyslogPlugin', type: 'Syslog', status: '启用', config: '{}', code: 'print("SyslogPlugin")' },
        { id: 2, name: 'KafkaPlugin', type: 'Kafka', status: '禁用', config: '{}', code: 'print("KafkaPlugin")' }
      ],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "",
      form: {},
      selectedRows: [],
      loading: false,
      detailVisible: false,
      selectedRow: {},
      pluginTypes: [
        { value: 'Syslog', label: 'Syslog' },
        { value: 'Kafka', label: 'Kafka' },
        { value: 'Http', label: 'Http' },
        { value: 'JDBC', label: 'JDBC' }
      ]
    };
  },
  methods: {
    fetchPlugins() {
      this.loading = true;
      setTimeout(() => {
        const { name, type } = this.queryForm;
        let filteredData = this.totalTableData;

        if (name) {
          filteredData = filteredData.filter(item => item.name.includes(name));
        }

        if (type) {
          filteredData = filteredData.filter(item => item.type === type);
        }

        this.total = filteredData.length;
        this.tableData = filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.loading = false;
      }, 1000);
    },
    resetData() {
      this.$refs.formRef.resetFields();
      this.fetchPlugins();
    },
    handleAdd() {
      this.dialogTitle = "新增插件";
      this.form = {
        code: '',
        status: '禁用'
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑插件";
      this.form = { ...row };
      this.dialogVisible = true;
    },
    handleEnableDisable(row) {
      row.status = row.status === '启用' ? '禁用' : '启用';
      this.$modal.loading('更新中...')
      setTimeout(() => {
        this.updatePlugin(row);
        this.$modal.closeLoading()
        this.$message({
          type: 'success',
          message: '插件状态已更新!'
        });
      }, 1000)
    },
    handleTest(row) {
      // 调用测试接口
      console.log('测试插件', row);
      this.$modal.loading('测试中...')
      setTimeout(() => {
        this.$modal.closeLoading()
        this.$message({
          type: 'success',
          message: '插件已测试成功!'
        });
      }, 1000)

    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该插件信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.tableData.indexOf(row);
        if (index > -1) {
          this.tableData.splice(index, 1);
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的插件信息!'
        });
        return;
      }
      this.$confirm('此操作将永久删除选中的插件信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(row => !this.selectedRows.includes(row));
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchPlugins();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchPlugins();
    },
    handleSubmit(formData) {
      if (this.dialogTitle === "新增插件") {
        console.log(formData);
        formData.id = this.totalTableData.length ? this.totalTableData[this.totalTableData.length - 1].id + 1 : 1;
        this.totalTableData.unshift({ ...formData });
        this.tableData.unshift({ ...formData });
      } else {
        const index = this.tableData.findIndex(row => row.id === formData.id);
        if (index > -1) {
          this.$set(this.tableData, index, { ...formData });
        }
      }
      this.dialogVisible = false;
    },
    updatePlugin(plugin) {
      const index = this.totalTableData.findIndex(row => row.id === plugin.id);
      if (index > -1) {
        this.$set(this.totalTableData, index, { ...plugin });
      }
    }
  },
  mounted() {
    // 页面加载时不自动获取数据，等待用户点击同步按钮
    this.fetchPlugins();
  }
};
</script>

<style scoped lang="scss">
.plugin-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;

  .el-row {
    margin-bottom: 20px;
  }

  .el-table {
    flex: 1;
    margin-bottom: 20px;
  }
}
</style>
